﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Diagnostics;
using System.Web.UI;
using System.Net;
using System.IO;
using System.ComponentModel;
[assembly: WebResource("Kevin.Controls.DialogWindow.DialogWindow.js", "text/javascript")]
[assembly: WebResource("Kevin.Controls.Dialog.css", "text/css", PerformSubstitution = true)]

namespace Kevin.Controls
{
    [ClientScriptResource("Kevin.Controls.DialogWindow", "Kevin.Controls.DialogWindow.DialogWindow.js")]
    [ClientCssResource("Kevin.Controls.Dialog.css")]
    [RequiredScript(typeof(PopupControlExtender))]
    [RequiredScript(typeof(ModalPopupExtender))]
    [RequiredScript(typeof(KevinPublicScript))]
    [ParseChildren(typeof(Kevin.Controls.ParameterItem), DefaultProperty = "Parameters", ChildrenAsProperties = true)]
    public class DialogWindow : ScriptControlBase
    {
        public DialogWindow()
            : base(true, System.Web.UI.HtmlTextWriterTag.Div)
        { }

        protected override string SaveClientState()
        {
            try
            {
                List<ClientQueryMethod> clientQueryMethodes = new List<ClientQueryMethod>();
                /*
                if (this.ParameterControls != null)
                {
                    string[] Controls = this.ParameterControls.Split(',');
                    string[] Methodes = this.ParameterMethods.Split(',');
                    for (int i = 0; i < Controls.Length; i++)
                    {
                        string strCtrl = Controls[i];
                        Control ctr = this.FindControl(strCtrl);
                        if (ctr != null)
                        {
                            //如果是服务器端控件则先获取其客户端ID，并
                            if (string.IsNullOrEmpty(Methodes[i]))
                            {
                                clientQueryMethodes.Add(new ClientQueryMethod(GetClientControlDataMethod(ctr), ctr.ClientID));
                            }
                            else
                            {
                                clientQueryMethodes.Add(new ClientQueryMethod(Methodes[i] + "('" + ctr.ClientID + "')", ctr.ClientID));
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(strCtrl))
                            {
                                clientQueryMethodes.Add(new ClientQueryMethod("_getControlValue('" + strCtrl + "')", strCtrl));
                            }
                        }
                    }
                }
                //*/
                string[] queryStringItems = this.URL.Split('?');
                //int queryStringItemNumber = 0;
                int controlPatameterItemNumber = 0;

                this.URL = queryStringItems[0] + "?KevinXi=KevinXi";
                //queryStringItemNumber = queryStringItems[1].Split('&').Length;

                foreach (ParameterItem item in this.Parameters)
                {
                    switch (item.QueryStringParameterType)
                    {
                        case QueryStringType.Control:
                            ControlPara para = item as ControlPara;
                            Control ctr = this.FindControl(para.ControlID);
                            if (ctr != null)
                            {
                                if (string.IsNullOrEmpty(para.ClientMethod))
                                {
                                    clientQueryMethodes.Add(new ClientQueryMethod(GetClientControlDataMethod(ctr), ctr.ClientID));
                                }
                                else
                                {
                                    clientQueryMethodes.Add(new ClientQueryMethod(para.ClientMethod + "('" + ctr.ClientID + "')", ctr.ClientID));
                                }
                            }
                            else
                            {
                                clientQueryMethodes.Add(new ClientQueryMethod("_getControlValue('" + para.ControlID + "')", para.ControlID));
                            }
                            this.URL += "&" + para.QueryStringName + "={" + controlPatameterItemNumber + "}";
                            controlPatameterItemNumber++;
                            break;
                        case QueryStringType.QueryString:
                            QueryStringPara paraQ = item as QueryStringPara;
                            this.URL += "&" + (string.IsNullOrEmpty(paraQ.QueryStringName) ? paraQ.QueryStringID : paraQ.QueryStringName) + "=" + Page.Request.QueryString[paraQ.QueryStringID];
                            break;
                        case QueryStringType.Session:
                            SessionPara paraS = item as SessionPara;
                            this.URL += "&" + paraS.QueryStringName + "=" + Page.Session[paraS.SessionID].ToString();
                            break;
                        case QueryStringType.Const:
                            ConstPara paraC = item as ConstPara;
                            this.URL += "&" + paraC.QueryStringName + "=" + paraC.Value;
                            break;
                        default:
                            break;
                    }
                    // queryStringItemNumber++;
                }
                //如果没有指定弹出窗口所停靠的控件ID，则在屏幕正中央弹出窗体
                if (string.IsNullOrEmpty(this.ParentElementID))
                {
                    this.Position = PositioningMode.Center;
                }
                else
                {
                    //如果指定了弹出窗口所停靠的控件ID，则尝试去获取其客户端ID
                    Control ctr = this.FindControl(this.ParentElementID);
                    if (ctr != null)
                    {
                        this.ParentElementID = ctr.ClientID;
                    }
                }
                DialogClientState state = new DialogClientState(this.URL);
                state.ClientQueryMethods = clientQueryMethodes;
                return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(state);
            }
            catch (Exception ex)
            {
                throw new Exception("保存客户端状态出错：" + ex.Message + ex.StackTrace);
            }

        }
        /// <summary>
        /// 获取控件的客户端取值方法，因为弹出窗体时，需想URL传递参数，而这些参数可能是当前页面上某些控件的值
        /// </summary>
        /// <param name="ctr"></param>
        /// <returns></returns>
        private string GetClientControlDataMethod(Control ctr)
        {

            string clientMethod = "";
            if (ctr is TextBox)
                clientMethod = " _getNormalValue('" + ctr.ClientID + "'); ";
            if (ctr is Label)
                clientMethod = " _getSpanValue('" + ctr.ClientID + "');";
            if (ctr is DropDownList)
                clientMethod = " _getDropDownListValue('" + ctr.ClientID + "'); ";
            if (ctr is CodeNameSelect)
                clientMethod = @"_getCodeNameSelectValue('" + ctr.ClientID + "');";
            if (ctr is CheckBox)
                clientMethod = " _getChecked('" + ctr.ClientID + "'); ";
            return clientMethod;
        }
        /// <summary>
        /// 获取客户端状态
        /// </summary>
        /// <param name="clientState"></param>
        protected override void LoadClientState(string clientState)
        {
            base.LoadClientState(clientState);
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (!DesignMode)
            {
                Page.ClientScript.GetCallbackEventReference(this, "", "", "");
            }
            base.OnPreRender(e);
            string[] controls = this.ControlID.Split(',');
            string controlID = "";
            foreach (string strID in controls)
            {
                Control ct = this.FindControl(strID);
                if (ct != null)
                {
                    controlID = controlID+ct.ClientID + ",";
                }
                else
                {
                    controlID = controlID+strID + ",";
                }
            }
            this.ControlID = controlID.Substring(0, controlID.Length - 1);

        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }

        /// <summary>
        /// 弹出窗体的位置，默认为屏幕正中央
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("Position")]
        public PositioningMode Position
        {
            get { return GetPropertyValue<PositioningMode>("Position", PositioningMode.Center); }
            set { SetPropertyValue<PositioningMode>("Position", value); }
        }

        /// <summary>
        /// 弹出窗体的位置所依赖的控件ID，如果没有指定此控件ID则Position属性指定无效，并弹出到屏幕正中央
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("ParentElementID")]
        public string ParentElementID
        {
            get { return GetPropertyValue<string>("ParentElementID", ""); }
            set { SetPropertyValue<string>("ParentElementID", value); }
        }
        /// <summary>
        /// 是否总是打开新内容
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("AlwaysNewContent")]
        public bool AlwaysNewContent
        {
            get { return GetPropertyValue<bool>("AlwaysNewContent", false); }
            set { SetPropertyValue<bool>("AlwaysNewContent", value); }
        }
        /// <summary>
        /// 弹出窗体中需加载的页面地址
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("Url")]
        public string URL
        {
            get
            {
                string strUrl = GetPropertyValue<string>("URL", "").Trim();

                if (!strUrl.StartsWith("http", true, null) && !string.IsNullOrEmpty(strUrl))
                {
                    //strUrl = "http://" + Page.Request.Url.Authority + ResolveUrl(strUrl);
                }

                return strUrl;
            }
            set { SetPropertyValue<string>("URL", value); }
        }

        /// <summary>
        /// 这个已经弃用了
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("UrlContent")]
        public string UrlContent
        {
            get { return ""; }
            //get { return GetPropertyValue<string>("UrlContent", GetContentFromUrl("http://"+Page.Request.Url.Authority +ResolveUrl(this.URL))); }
            set { SetPropertyValue<string>("UrlContent", value); }
        }
        /// <summary>
        /// 触发弹出事件的控件ID
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("ControlID")]
        public string ControlID
        {
            get 
            { 
                return GetPropertyValue<string>("ControlID", ""); 
            }
            set 
            {
                //Control ctr = this.FindControl(value);
                SetPropertyValue<string>("ControlID", value); 
            }
        }


        /// <summary>
        /// 弹出窗的标题 默认为：神州数码(苏州)国信有限公司
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("Title")]
        public string Title
        {
            get { return GetPropertyValue<string>("Title", "苏州捷安信息科技有限公司"); }
            set { SetPropertyValue<string>("Title", value); }
        }
        /// <summary>
        /// 弹出窗的宽度
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("Width")]
        public new Unit Width
        {
            get { return GetPropertyValue<Unit>("Width", 400); }
            set { SetPropertyValue<Unit>("Width", value); }
        }


        /// <summary>
        /// 弹出窗的高度
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("Height")]
        public new Unit Height
        {
            get { return GetPropertyValue<Unit>("Height", 300); }
            set { SetPropertyValue<Unit>("Height", value); }
        }

        private ParameterItemCollection _parameters = new ParameterItemCollection();
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ParameterItemCollection Parameters
        {
            get { return _parameters; }
        }

        /*
        /// <summary>
        /// 对于NavigateUrl中参数值所依赖的控件
        /// </summary>
        public string ParameterControls
        {
            get;
            set;
        }

        /// <summary>
        /// 对ParameterControls中若干控件的客户端取值方法
        /// </summary>
        public string ParameterMethods
        {
            get;
            set;
        }
        //*/
        /// <summary>
        /// 弹出窗体的样式名称[默认名为：dialog]
        /// </summary>
        [ExtenderControlProperty]
        [ClientPropertyName("DialogClassName")]
        public string DialogClassName
        {
            get { return GetPropertyValue<string>("DialogClassName", "dialogNormal"); }
            set { SetPropertyValue<string>("DialogClassName", value); }
        }
        /// <summary>
        /// 根据控件的ID在本页面中找到该服务器控件
        /// </summary>
        /// <param name="rootControl"></param>
        /// <param name="idPath"></param>
        /// <returns></returns>
        private Control FindControlByPath(Control rootControl, string idPath)
        {
            int depth = 0;
            string[] idPaths = idPath.Split('.');
            while (idPaths.Length > depth)
            {
                rootControl = rootControl.FindControl(idPaths[depth]);
                depth++;
            }
            return rootControl;
        }

        #region Helper

        [DebuggerStepThrough]
        protected V GetPropertyValue<V>(string propertyName, V nullValue)
        {
            if (ViewState[propertyName] == null)
            {
                return nullValue;
            }
            return (V)ViewState[propertyName];
        }


        /// <summary>
        /// Save the property value in the ViewState
        /// </summary>
        /// <typeparam name="V">Property type</typeparam>
        /// <param name="propertyName">Property name</param>
        /// <param name="value">Value</param>
        [DebuggerStepThrough]
        protected void SetPropertyValue<V>(string propertyName, V value)
        {
            ViewState[propertyName] = value;
        }

        #endregion
    }
}
